#ifndef __TIME_APP_H
#define __TIME_APP_H

#include "./exec_app.h"
#include "./handler.h"
#include <QTimerEvent>
#include <memory>
#include <unordered_map>

class TimeApp : public ExecApp {

public:
    TimeApp(int argc, char *argv[]) : ExecApp(argc, argv) {}

    int post_delay(int ms, HandlerPtr &&handler) {
        int id = startTimer(ms);
        m_map.insert({id, std::move(handler)});
        return id;
    }

    void remove_timer(int id) {
        killTimer(id);
        m_map.erase(id);
    }

protected:
    void timerEvent(QTimerEvent *event) override {
        int id = event->timerId();
        auto iter = m_map.find(id);
        if (iter == m_map.end()) {
            return;
        }
        iter->second->exec();
    }

private:
    std::unordered_map<int, HandlerPtr> m_map;
};

// call in ui thread
template <typename F> inline int run_on_delay(int ms, F &&f) {
    return static_cast<TimeApp *>(qApp)->post_delay(ms, make_handler(std::move(f)));
}

inline void remove_timer(int id) {
    return static_cast<TimeApp *>(qApp)->remove_timer(id);
}

#endif
